﻿Imports ZedGraph

'/*
' * FAHWatch7  Copyright Marvin Westmaas ( mtm )
' *
' * This program is free software; you can redistribute it and/or
' * modify it under the terms of the GNU General Public License
' * as published by the Free Software Foundation; version 2
' * of the License. See the included file GPLv2.TXT.
' * 
' * This program is distributed in the hope that it will be useful,
' * but WITHOUT ANY WARRANTY; without even the implied warranty of
' * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' * GNU General Public License for more details.
' * 
' * You should have received a copy of the GNU General Public License
' * along with this program; if not, write to the Free Software
' * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
' */
'/*
Public Class frmHistory
#Region "Declarations"
    Private bManual As Boolean = False
    Private m_SelectedWU As clsWU
    Private lWU_Identifier As New List(Of String)
    Private m_MyStatistics As New clsStatistics.sClient
#End Region
#Region "Historical listview functions"
    Private Function lvItemForHistory(ByVal ClientName As String, ByVal WU As clsWU) As ListViewItem
        Try
            Dim nI As New ListViewItem
            nI.BackColor = Color.LightBlue
            nI.Text = ClientName
            nI.SubItems.Add(WU.Slot)
            nI.SubItems.Add(WU.HW)
            nI.SubItems.Add(WU.PRCG)
            nI.SubItems.Add(WU.dtDownloaded.ToString)
            nI.SubItems.Add(WU.dtSubmitted.ToString)
            nI.SubItems.Add(WU.WS)
            nI.SubItems.Add(WU.Core)
            nI.SubItems.Add(WU.CoreVersion)
            nI.SubItems.Add(WU.CoreStatus)
            If WU.CoreStatus <> "" AndAlso (Not WU.CoreStatus.Contains("(100") Or Not WU.CoreStatus.Contains("FINISHED_UNIT")) Then
                nI.BackColor = Color.Red
            End If
            nI.SubItems.Add(WU.ServerResponce)
            If Not WU.ServerResponce.Contains("WORK_ACK") And Not nI.BackColor = Color.Red Then
                nI.BackColor = Color.LightGray
            End If
            nI.SubItems.Add(WU.Credit)
            nI.SubItems.Add(WU.PPD)
            nI.SubItems.Add(WU.UploadSize)
            nI.SubItems.Add(WU.UploadSpeed)
            If WU.bHasRestarted Then
                If Not nI.BackColor = Color.Red Then nI.BackColor = Color.Yellow
            End If
            nI.Tag = WU.unit
            Return nI
        Catch ex As Exception
            WriteError(ex.Message, Err)
            Return New ListViewItem
        End Try
    End Function
    Private Sub lvWU_DoubleClick(sender As Object, e As System.EventArgs) Handles lvWU.MouseDoubleClick
        Try
            'Allow a 'detailed form' displaying both frame info and wu details?
            If IsNothing(m_SelectedWU) Then Exit Sub
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub lvWU_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles lvWU.SelectedIndexChanged
        Try
            If lvWU.SelectedItems.Count = 0 Then
                m_SelectedWU = Nothing
                rtLogSnippet.Clear()
                rtPerformanceStatistics.Clear()
                zgProject.MasterPane.PaneList.Clear()
                zgProject.GraphPane = New GraphPane
                Exit Sub
            Else
                Dim sTmp As String = lWU_Identifier(lvWU.SelectedIndices(0)).ToString
                Dim tClient As String = sTmp.Substring(0, sTmp.IndexOf("##"))
                Dim tSlot As String = sTmp.Substring(sTmp.IndexOf("##") + 2, 2)
                Dim tUnit As String = sTmp.Substring(sTmp.LastIndexOf("##") + 2)
                m_SelectedWU = sqdata.WorkUnit(tClient, tSlot, tUnit)
                If mySettings.ViewDetails Then
                    Detail_WU()
                    Detail_zGraph()
                    Detail_PerformanceStatistics()
                Else
                    If zGraph.IsFormVisible Then zGraph.ShowWUFrames(m_SelectedWU)
                    If wuSnippet.IsFormVisible Then wuSnippet.ShowSnippet(m_SelectedWU)
                End If
            End If
            lvWU.EnsureVisible(lvWU.SelectedIndices(0))
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
#End Region
    Public Function Fill(Optional sqlQuery As String = "") As Boolean
        Try
            'Hide tool windows
            wuSnippet.HideForm()
            zGraph.HideForm()
            'Run query
            Me.UseWaitCursor = True
            Dim iLeft As Integer = CInt(Math.Round((Me.ClientSize.Width - 343) / 2, 0))
            Dim iTop As Integer = CInt(Math.Round((Me.ClientSize.Height - 111) / 2, 0))
            Bussy.ShowForm("Filling history... please wait", New Size(343, 111), New Point(iLeft, iTop))
            Application.DoEvents()
            lvWU.SuspendLayout()
            lvWU.Items.Clear()
            lWU_Identifier.Clear()
            m_SelectedWU = Nothing
            If sqlQuery = "" Then
                'Dim lWUS As List(Of clsWU) = sqdata.WorkUnits(New Dictionary(Of String, String))
                Dim lWUS As List(Of clsWU) = sqdata.WorkUnits("")
                For Each wu As clsWU In lWUS
                    If Not lWU_Identifier.Contains(wu.ClientName & "##" & wu.Slot & "##" & wu.unit) Then
                        lWU_Identifier.Add(wu.ClientName & "##" & wu.Slot & "##" & wu.unit)
                    Else
                        'MsgBox("huh?")
                    End If
                    Dim nI As ListViewItem = lvItemForHistory(wu.ClientName, wu)
                    lvWU.Items.Add(nI)
                Next
                m_MyStatistics = Statistics.Statistics(lWUS)
            Else
                Dim lWUS As List(Of clsWU) = sqdata.WorkUnits(sqlQuery)
                For Each wu In sqdata.WorkUnits(sqlQuery)
                    If Not lWU_Identifier.Contains(wu.ClientName & "##" & wu.Slot & "##" & wu.unit) Then
                        lWU_Identifier.Add(wu.ClientName & "##" & wu.Slot & "##" & wu.unit)
                    Else
                        MsgBox("huh?")
                    End If
                    Dim nI As ListViewItem = lvItemForHistory(wu.ClientName, wu)
                    lvWU.Items.Add(nI)
                Next
                m_MyStatistics = Statistics.Statistics(lWUS)
            End If

            lvWU.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize)
            For xInt As Int32 = 0 To lvWU.Columns.Count - 1
                lvWU.Columns(xInt).Tag = lvWU.Columns(xInt).Width
            Next
            lvWU.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)
            For xint As Int32 = 0 To lvWU.Columns.Count - 1
                If lvWU.Columns(xint).Width < CInt(lvWU.Columns(xint).Tag) Then lvWU.Columns(xint).Width = CInt(lvWU.Columns(xint).Tag)
            Next
            lvWU.ResumeLayout()
            tsStatistics.Text = "Total WUs: " & m_MyStatistics.WU_Completed & " Failed: " & m_MyStatistics.WU_EUE & " Succesrate: " & m_MyStatistics.SuccesRate & "Total computation time: " & m_MyStatistics.ComputationTime & " Avg PPD: " & m_MyStatistics.AveragePPD
            Bussy.CloseForm()
            Me.UseWaitCursor = False
            Me.Focus()
            Return CBool(lWU_Identifier.Count > 0)
        Catch ex As Exception
            Me.Enabled = True
            WriteError(ex.Message, Err)
            Return False
        End Try
    End Function
    Private Sub frmHistory_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
        Try
            RefreshFilterMenu()
            Fill()
        Catch ex As Exception

        End Try
    End Sub
    Public Sub RefreshFilterMenu()
        Try
            'remove old event handlers
            For Each dItem As ToolStripMenuItem In tsiFilters.DropDownItems
                RemoveHandler dItem.Click, AddressOf HandleFilterItemClicked
            Next
            tsiFilters.DropDownItems.Clear()
            'Add new one's
            For Each fName In sqlFilters.FilterNames
                Dim nItem As New ToolStripMenuItem(fName, Nothing, New EventHandler(AddressOf HandleFilterItemClicked))
                tsiFilters.DropDownItems.Add(nItem)
            Next
        Catch ex As Exception

        End Try
    End Sub
#Region "Menu"

    Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        Try
            about.ShowAbout(Me)
        Catch ex As Exception

        End Try
    End Sub

    Private Sub LicenseToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles LicenseToolStripMenuItem.Click
        Try
            license.ShowLicense(Me)
        Catch ex As Exception

        End Try
    End Sub
    Private Sub ProjectInfoToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ProjectInfoToolStripMenuItem.Click
        Try
            pBrowser.ShowBrowser()
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub ZGraphToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ZGraphToolStripMenuItem.Click
        Try
            If zGraph.IsFormVisible Then
                zGraph.HideForm()
            Else
                zGraph.ShowWUFrames(m_SelectedWU, Me)
            End If
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub LogSnippetToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles LogSnippetToolStripMenuItem.Click
        Try
            If wuSnippet.IsFormVisible Then
                wuSnippet.HideForm()
            Else
                wuSnippet.ShowSnippet(m_SelectedWU, Me)
            End If
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub ParseToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs)
        Try
            Me.Cursor = Cursors.WaitCursor
            logParser.ParseLogs()
            Me.Cursor = Cursors.Default
            Fill()
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub frmHistory_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Try

        Catch ex As Exception

        End Try
    End Sub
    Private Sub cmLVUnits_Opening(sender As System.Object, e As System.ComponentModel.CancelEventArgs) Handles cmLVUnits.Opening
        Try
            ZGraphToolStripMenuItem.Checked = zGraph.IsFormVisible
            LogSnippetToolStripMenuItem.Checked = wuSnippet.IsFormVisible
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
#End Region
    Public Sub HandleFilterItemClicked(Sender As Object, e As System.EventArgs)
        Try
            Dim strQuery As String = sqlFilters.sql(CType(Sender, ToolStripMenuItem).Text)
            If Not Fill(strQuery) Then
                If sqdata.LastSQL <> String.Empty Then
                    MsgBox("This filter seems to return an SQL exception. Check the syntax of " & CType(Sender, ToolStripMenuItem).Text & "!", CType(MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation, MsgBoxStyle), "SQL exception")
                End If
            End If
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub EditFiltersToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles EditFiltersToolStripMenuItem.Click
        Try
            sqlFilters.ShowForm(Me)
            RefreshFilterMenu()
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub

    Private Sub ClearToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ClearToolStripMenuItem.Click
        Try
            Fill()
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub


    Private Sub GeneralToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles GeneralToolStripMenuItem.Click
        mySettings.ShowOptionsForm(Me)
    End Sub

    Private Sub NotificationsToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles NotificationsToolStripMenuItem.Click
        mySettings.ShowNotifyForm(Me)
    End Sub

    Private Sub CloseToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CloseToolStripMenuItem.Click
        If mySettings.MinimizeToTray Then
            Tray.ShowIcon()
            Me.Hide()
        Else
            Me.Close()
        End If
    End Sub
    Private Sub Detail_zGraph()
        Try
            Dim ppProject As New ZedGraph.PointPairList
            For xInt As Int32 = 0 To m_SelectedWU.Frames.Count - 2
                Console.WriteLine(xInt)
                Dim tsFrame As TimeSpan = m_SelectedWU.Frames(xInt + 1).FrameDT - m_SelectedWU.Frames(xInt).FrameDT
                ppProject.Add(New XDate(m_SelectedWU.Frames(xInt).FrameDT), tsFrame.TotalDays)
            Next
            zgProject.MasterPane.PaneList.Clear()
            Dim mPane As New GraphPane
            mPane.AddCurve("", ppProject, Color.Blue)
            mPane.XAxis.Type = ZedGraph.AxisType.Date
            mPane.YAxis.Type = AxisType.Date
            mPane.Rect = scDetail.Panel2.ClientRectangle
            zgProject.GraphPane = mPane
            zgProject.AxisChange()
            zgProject.Refresh()
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub Detail_PerformanceStatistics()
        Try
            rtPerformanceStatistics.Clear()
            clsStatistics.GenerateNewStatistics()
            rtPerformanceStatistics.Text = Statistics.CurrentStatistics.Report
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
    Private Sub Detail_WU()
        Try
            rtLogSnippet.Clear()
            rtLogSnippet.Text = m_SelectedWU.Report & Environment.NewLine & Environment.NewLine & m_SelectedWU.CoreSnippet
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub

    Private Sub ViewToolStripMenuItem_DropDownClosed(sender As Object, e As System.EventArgs) Handles ViewToolStripMenuItem.DropDownClosed
        Try
            scMain.Panel2Collapsed = Not mySettings.ViewDetails
        Catch ex As Exception

        End Try
    End Sub
    Private Sub ViewToolStripMenuItem_DropDownOpening(sender As Object, e As System.EventArgs) Handles ViewToolStripMenuItem.DropDownOpening
        Try
            If mySettings.HasSetting("history_detail") Then
                bManual = True
                If mySettings.ViewDetails Then
                    DetailedToolStripMenuItem.Checked = True
                    DefaultToolStripMenuItem.Checked = False
                Else
                    DetailedToolStripMenuItem.Checked = False
                    DefaultToolStripMenuItem.Checked = True
                End If
            End If
        Catch ex As Exception
            WriteError(ex.Message, Err)
        Finally
            bManual = True
        End Try
    End Sub
    Private Sub DetailedToolStripMenuItem_Click(sender As Object, e As System.EventArgs) Handles DetailedToolStripMenuItem.Click
        Try
            mySettings.ChangeSetting("history_detail", DetailedToolStripMenuItem.Checked.ToString)
            mySettings.SaveSettings()
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub

    Private Sub DefaultToolStripMenuItem_Click(sender As Object, e As System.EventArgs) Handles DefaultToolStripMenuItem.Click
        Try
            mySettings.ChangeSetting("history_detail", DetailedToolStripMenuItem.Checked.ToString)
            mySettings.SaveSettings()
        Catch ex As Exception
            WriteError(ex.Message, Err)
        End Try
    End Sub
End Class